package com.wangyadong.hobby.nio.charter2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class EchoClient {

    private final int port;
    private final String host;
    private EventLoopGroup eventLoopGroup;
    private Bootstrap bootstrap;

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public EchoClient(int port, String host) {
        this.host = host;
        this.port = port;
        eventLoopGroup = new NioEventLoopGroup();
    }


    public EventLoopGroup getEventLoopGroup() {
        return eventLoopGroup;
    }

    public Bootstrap start() throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new EchoClientHandler());
                    }
                });
        return bootstrap;
//            future.channel().closeFuture().sync();

    }

    public static void main(String[] args) throws InterruptedException {
        EchoClient echoClient = new EchoClient(16, "127.0.0.1");
        Bootstrap bootstrap = null;
        if (echoClient.getBootstrap() == null) {
            bootstrap = echoClient.start();
        }

        while (true) {
            ChannelFuture future = bootstrap.connect().sync();
            future.channel().writeAndFlush("王耀成功i哦你放心" + System.currentTimeMillis()).sync();
//            future.channel().closeFuture().sync();
//            echoClient.getEventLoopGroup().shutdownGracefully().sync();
        }

    }
}
